import React, { FC, Suspense } from "react";
import * as Type from '@/utils/index'
import { BrowserRouter, HashRouter, Route, Routes, Navigate } from "react-router-dom";

type Props = {
  routes: Type.RouterList
  mode?: 'history' | 'hash'
}
const Router: FC<Props> = ({ routes }) => {
  const renderRoutes = (arr: Type.RouterList) =>
    arr.map((item: Type.RouterItem, index: number) => (
      <Route key={index} path={item.path}
        element={item.to ? <Navigate to={item.to}></Navigate> : <item.element></item.element>}
      >
        {
          item.children && renderRoutes(item.children)
        }
      </Route>
    ))
    return (
      <Suspense>
        <Routes>
          {
            renderRoutes(routes)
          }
        </Routes>
      </Suspense>
    )
}

const App:FC<Props>=({routes,mode})=>
  mode==='history'?(
    <BrowserRouter><Router routes={routes}></Router></BrowserRouter>
  ):(
    <HashRouter><Router routes={routes}></Router></HashRouter>
  )

  export default App
